package com.example;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.scene.layout.HBox;

import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

public class AdminSemesterManagementController {
    @FXML private TableView<Semester> semesterTableView;
    @FXML private TableColumn<Semester, Integer> semesterIdColumn;
    @FXML private TableColumn<Semester, String> semesterNameColumn;
    @FXML private TableColumn<Semester, LocalDate> startDateColumn;
    @FXML private TableColumn<Semester, LocalDate> endDateColumn;
    @FXML private TableColumn<Semester, String> statusColumn;
    @FXML private TableColumn<Semester, Void> actionColumn;
    @FXML private TextField searchField;
    @FXML private ComboBox<Integer> pageSizeComboBox;
    @FXML private Pagination pagination;

    private SemesterDAO semesterDAO;
    private ObservableList<Semester> semesterList;
    private static final int DEFAULT_PAGE_SIZE = 10;

    @FXML
    public void initialize() {
        semesterDAO = new SemesterDAO();
        setupTable();
        setupPagination();
        loadSemesters();
    }

    private void setupTable() {
        semesterIdColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
        semesterNameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        startDateColumn.setCellValueFactory(new PropertyValueFactory<>("startDate"));
        endDateColumn.setCellValueFactory(new PropertyValueFactory<>("endDate"));
        statusColumn.setCellValueFactory(new PropertyValueFactory<>("status"));
        actionColumn.setCellFactory(createActionButtonCellFactory());
    }

    private void setupPagination() {
        pageSizeComboBox.getItems().addAll(5, 10, 20, 50);
        pageSizeComboBox.setValue(DEFAULT_PAGE_SIZE);
        pageSizeComboBox.setOnAction(e -> updatePagination());
    }

    private void loadSemesters() {
        semesterList = FXCollections.observableArrayList(semesterDAO.getAllSemesters());
        updatePagination();
    }

    private void updatePagination() {
        int pageSize = pageSizeComboBox.getValue();
        int totalPages = (int) Math.ceil((double) semesterList.size() / pageSize);
        pagination.setPageCount(totalPages);
        pagination.setPageFactory(pageIndex -> {
            int fromIndex = pageIndex * pageSize;
            int toIndex = Math.min(fromIndex + pageSize, semesterList.size());
            semesterTableView.setItems(FXCollections.observableArrayList(semesterList.subList(fromIndex, toIndex)));
            return new HBox();
        });
    }

    private Callback<TableColumn<Semester, Void>, TableCell<Semester, Void>> createActionButtonCellFactory() {
        return new Callback<>() {
            @Override
            public TableCell<Semester, Void> call(TableColumn<Semester, Void> param) {
                return new TableCell<>() {
                    private final Button editButton = new Button("编辑");
                    private final Button deleteButton = new Button("删除");

                    {
                        editButton.setOnAction(event -> {
                            Semester semester = getTableView().getItems().get(getIndex());
                            handleEditSemester(semester);
                        });

                        deleteButton.setOnAction(event -> {
                            Semester semester = getTableView().getItems().get(getIndex());
                            handleDeleteSemester(semester);
                        });
                    }

                    @Override
                    protected void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setGraphic(null);
                        } else {
                            HBox buttons = new HBox(5, editButton, deleteButton);
                            setGraphic(buttons);
                        }
                    }
                };
            }
        };
    }

    @FXML
    private void handleAddSemester() {
        showSemesterDialog(null);
    }

    private void handleEditSemester(Semester semester) {
        showSemesterDialog(semester);
    }

    private void handleDeleteSemester(Semester semester) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("确认删除");
        alert.setHeaderText(null);
        alert.setContentText("确定要删除学期 " + semester.getName() + " 吗？");

        Optional<ButtonType> result = alert.showAndWait();
        if (result.isPresent() && result.get() == ButtonType.OK) {
            if (semesterDAO.deleteSemester(semester.getId())) {
                loadSemesters();
                showAlert(Alert.AlertType.INFORMATION, "成功", "学期已删除");
            } else {
                showAlert(Alert.AlertType.ERROR, "错误", "删除学期失败");
            }
        }
    }

    @FXML
    private void handleSearch() {
        String keyword = searchField.getText().trim();
        if (!keyword.isEmpty()) {
            List<Semester> searchResults = semesterDAO.searchSemesters(keyword);
            semesterList = FXCollections.observableArrayList(searchResults);
            updatePagination();
        } else {
            loadSemesters();
        }
    }

    private void showSemesterDialog(Semester semester) {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("SemesterDialog.fxml"));
            Parent root = loader.load();

            SemesterDialogController controller = loader.getController();
            controller.setSemester(semester);

            Stage dialogStage = new Stage();
            dialogStage.setTitle(semester == null ? "添加学期" : "编辑学期");
            dialogStage.initModality(Modality.APPLICATION_MODAL);
            dialogStage.setScene(new Scene(root));

            controller.setDialogStage(dialogStage);
            dialogStage.showAndWait();

            if (controller.isConfirmed()) {
                loadSemesters();
            }
        } catch (IOException e) {
            e.printStackTrace();
            showAlert(Alert.AlertType.ERROR, "错误", "无法打开学期编辑对话框");
        }
    }

    private void showAlert(Alert.AlertType type, String title, String content) {
        Alert alert = new Alert(type);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }
} 